package edu.jhu.cs.oose.scheduleit.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import edu.jhu.cs.oose.scheduleit.dao.UserScheduleDao;
import edu.jhu.cs.oose.scheduleit.util.ScheduleType;
import edu.jhu.cs.oose.scheduleit.vo.Schedule;
import edu.jhu.cs.oose.scheduleit.vo.UserSchedule;
/**
 * The implementation class of the UserScheduleDao interface
 * @author oosegroup2
 *
 */
public class UserScheduleDaoImpl implements UserScheduleDao{
	
	private HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	public void save(UserSchedule userSchedule) throws DataAccessException{
		this.hibernateTemplate.saveOrUpdate(userSchedule);
	}

	public void delete(Schedule schedule) throws DataAccessException{
		Session session = null;
		StringBuilder queryString = new StringBuilder("Delete from UserSchedule where schedule_id =");		
		queryString.append(schedule.getId());
		if (schedule.getType() == ScheduleType.SUBSCRIBED){
			queryString.append(" and type ='"+ScheduleType.SUBSCRIBED+"'");
		}
		try {		
			session = this.hibernateTemplate.getSessionFactory().openSession();
			SQLQuery sqlQuery = session.createSQLQuery(queryString.toString());
			sqlQuery.executeUpdate();
		} catch (HibernateException e) {
			throw e;
		} finally{
			queryString.setLength(0);
			if (session != null && session.isOpen()){
				session.close();
			}
		}
	}
}
